/*
 * @Author: linxun 
 * @Date: 2021-03-09 15:45:49 
 * @Last Modified by: linxun
 * @Last Modified time: 2021-06-04 09:46:32
 * @Description: 图片原图展示
 */

import React, { useState, useEffect } from 'react';
import { Button, Modal, Switch } from 'antd';
import { onImgError } from '@/utils/utils';

import styles from './ImageModal.less';

const ImageModal = props => {
  const { visible, cancel, curImage, imgInfo } = props;
  const { labelFile } = curImage;
  const [openLabel, setOpenLabel] = useState(false);
  const [hasLabel, setHasLabel] = useState(false);
  const [canvasImgUrl, setCanvasImgUrl] = useState('');

  const generateImg = () => {
    const img = new Image();
    img.setAttribute('crossOrigin', 'anonymous');
    img.src = curImage.url;
    img.onload = () => drawCanvas(img);
  };

  const drawCanvas = img => {
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');

    const drawLine = (x, y) => {
      ctx.lineTo(x, y);
      ctx.stroke();
    };

    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img, 0, 0);

    ctx.strokeStyle = '#fff';
    ctx.fillStyle = 'rgba(255,255,255,0.3)';
    ctx.beginPath();
    ctx.moveTo(labelFile[0]?.x, labelFile[0]?.y);
    for (let i = 1; i < labelFile.length; i++) {
      drawLine(labelFile[i]?.x, labelFile[i]?.y);
    }
    ctx.fill();
    ctx.closePath();
    setCanvasImgUrl(canvas.toDataURL('image/png'));
  };

  // useEffect(() => {
  //   const hasLabel = labelFile && Array.isArray(labelFile);
  //   setOpenLabel(hasLabel);
  //   setHasLabel(hasLabel);
  //   if (hasLabel) {
  //     generateImg();
  //   }
  // }, [curImage]);

  return (
    <Modal
      title={openLabel ? '标注图片' : '原始图片'}
      visible={visible}
      onCancel={cancel}
      footer={<Button type='primary' onClick={cancel}>关闭</Button>}
      maskClosable={false}
      width='80%'
      style={{ maxWidth: 1200 }}
    >
      {imgInfo || null}
      <div className={styles.box}>
        <div className={`${styles.imgBox} ${curImage.txt ? styles.autoWidthImgBox : ''}`}>
          {openLabel && canvasImgUrl
            ? <img src={canvasImgUrl} alt={curImage.fileName} onError={onImgError} />
            : <img src={curImage.url} alt={curImage.fileName} onError={onImgError} />
          }
        </div>
        {curImage.txt &&
          <div className={styles.txtBox}><pre>{curImage.txt}</pre></div>
        }
      </div>
      {/* {hasLabel &&
        <div className={styles.switchBox}>
          标注标签：<Switch checked={openLabel} onChange={checked => setOpenLabel(checked)} />
        </div>
      } */}
      <canvas id='canvas' className={styles.canvas}></canvas>
    </Modal>
  )
}

export default ImageModal;